package com.dz.scrm.mvp.ui;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.WebSocket;
import okhttp3.WebSocketListener;
import okio.ByteString;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.ContentResolver;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Message;
import android.provider.CallLog;
import android.provider.ContactsContract;
import android.telephony.SubscriptionManager;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.widget.Toast;

import com.dz.scrm.R;
import com.dz.scrm.app.config.HttpHeaderInterceptor;
import com.dz.scrm.app.config.webSocketInterceptor;
import com.dz.scrm.mvp.model.entity.CallInfo;
import com.dz.scrm.utils.AppUtils;
import com.dz.scrm.utils.CallInfoService;
import com.dz.scrm.utils.DZWebSocketClient;
import com.dz.scrm.utils.PhonePlaceUtils;
import com.dz.scrm.utils.SharedPreferencesUtil;
import com.dz.scrm.utils.UploadUtil;
import com.dz.scrm.utils.WebSocketUtil;
import com.google.gson.Gson;
import com.miui.enterprise.sdk.ApplicationManager;
import com.miui.enterprise.sdk.PhoneManager;

import org.java_websocket.client.WebSocketClient;
import org.java_websocket.handshake.ServerHandshake;
import org.json.JSONException;

import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import static com.dz.scrm.mvp.model.api.ApiKt.APP_UPLOAD_FILE_URL;
import static com.dz.scrm.mvp.model.api.ApiKt.APP_WEBSOCKET_URL;
import static org.litepal.LitePalApplication.getContext;

public class MainActivity extends AppCompatActivity {
    private List<Map<String, String>> dataList;
    private ContentResolver resolver;
    private Uri callUri = CallLog.Calls.CONTENT_URI;
    private String[] columns = {CallLog.Calls.CACHED_NAME// 通话记录的联系人
            , CallLog.Calls.NUMBER// 通话记录的电话号码
            , CallLog.Calls.DATE// 通话记录的日期
            , CallLog.Calls.DURATION// 通话时长
            , CallLog.Calls.TYPE};// 通话类型}
    private String mobile;//被授权人电话号码

    private Request request;
    private OkHttpClient client;
    private WebSocket mWebSocket;
    private WebSocketClient webSocketClient;
    private String TAG = "HH";

    private StringBuffer sb = new StringBuffer();

    @SuppressLint("MissingPermission")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        initSDKPermission();
//        LoggerUtils.v("MainActivity:  ---------");
//        PhoneManager manager = PhoneManager.getInstance();

        getCallHistoryList(this, 5);

        List<CallInfo> CallInfo = CallInfoService.getCallInfos(this);
        Log.e("YY","-- > "+new Gson().toJson(CallInfo));

//        Log.e("HH", "phone "+PhonePlaceUtils.parsePhoneAddress("15071131177"));
        new Thread(new Runnable() {
            @Override
            public void run() {
                PhonePlaceUtils.Phone phone = null;
                try {
                    phone = PhonePlaceUtils.parsePhone("15071477498");
                    Log.e("HH", "phone ->" + new Gson().toJson(phone));
                } catch (IOException e) {
                    e.printStackTrace();
                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }
        }).start();

//        getContentCallLog();

//        getDataList();
//        Log.e("HH","name -1SSS1111 > ");
        TelephonyManager tm = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
//            String NAME = tm.getSimCarrierIdName().toString();
            //获取手机卡槽数量
            Log.e("HH", "name -11111 > " + "; num = " + tm.getPhoneCount());
//            String simSer = tm.getSimSerialNumber();
//
//            Log.e("HH","simSer > "+simSer);

            //获取当前SIM卡数量
            int activeSubscriptionInfoCount = SubscriptionManager.from(getContext()).getActiveSubscriptionInfoCount();
            Log.e("HH", "name -11111 > " + "; num = " + tm.getPhoneCount() + ";activeSubscriptionInfoCount = " +
                    "" + activeSubscriptionInfoCount);

        }
//        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) {
//            // TODO: Consider calling
//            //    ActivityCompat#requestPermissions
//            // here to request the missing permissions, and then overriding
//            //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
//            //                                          int[] grantResults)
//            // to handle the case where the user grants the permission. See the documentation
//            // for ActivityCompat#requestPermissions for more details.
//            Log.e("HH","NUM -11111 > ");
//            return;
//        }else {
//            Log.e("HH","NUM -222222 > ");
//            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP_MR1) {
//                Log.e("HH","NUM -3333333 > ");
//
//               int  num =  SubscriptionManager.from(MainActivity.this).getActiveSubscriptionInfoCount();
//               Log.e("HH","NUM - > "+num);
//            }
//        }

//        tm.getPhoneCount();

//        testWebSocket("wss://dev.dazhii.com/api/websocket/823/lh5gptae/websocket");


//        testWebSocket("wss://dev.dazhii.com/api/websocket");
//        URI serverURI = URI.create("wss://dev.dazhii.com/api/websocket/666/555gptae/websocket");
//        testSocket(serverURI);


        //https://dev.dazhii.com/api/websocket/user/queue/phone
//        URI uri = URI.create("ws://echo.websocket.org");
//        URI uri = URI.create("wss://dev.dazhii.com/api/websocket");
//        URI uri = URI.create("ws://123.207.136.134:9010/ajaxchattest");
//        URI uri = URI.create("wss://dev.dazhii.com/api/websocket/823/lh5gptae/websocket");
//        URI uri = URI.create("wss://dev.dazhii.com/api/websocket/user/queue/phone/websocket");
//        DZWebSocketClient client = new DZWebSocketClient(uri) {
//            @Override
//            public void onMessage(String message) {
//                //message就是接收到的消息
//                Log.e("JWebSocketClient", message);
//            }
//        };
//
//        try {
//            client.connectBlocking();
//        } catch (InterruptedException e) {
//            Log.e("JWebSocketClient","Exception "+e.getMessage());
//            e.printStackTrace();
//        }


//        WebSocketUtil.getDefault().connect("wss://dev.dazhii.com/api/websocket/823/lh5gptae/websocket");


//        File mDirectory = new File(Environment.getExternalStorageDirectory()+File.separator+
//                "linkid/log/log") ;
//        String url = "/storage/emulated/0/MIUI/sound_recorder/call_rec/10010(10010)_20210426165942.mp3";
//
//        Log.e("HH","mDirectory "+mDirectory.getName());
//        new Thread(new Runnable() {
//            @Override
//            public void run() {
//                try {
//                    UploadUtil.getInstance().upload(APP_UPLOAD_FILE_URL, mDirectory,
//                            SharedPreferencesUtil.getInfo(SharedPreferencesUtil.TOKEN), "64245485154851");
//                } catch (Exception e) {
//                    Log.e("HH","IOException "+e.getMessage());
//                    e.printStackTrace();
//                }
//            }
//        }).start();
//
    }


    private void testSocket(URI serverURI) {
        Log.e("HH", "testSocket - > ");
        Map<String, String> headers = new HashMap<>();
        headers.put("Dz-Auth", "bearer huanghai-test");
        webSocketClient = new WebSocketClient(serverURI, headers) {
            @Override
            public void onOpen(ServerHandshake handshakedata) {
                sb.append("onOpen at time：");
                sb.append(new Date());
                sb.append("服务器状态：");
                sb.append(handshakedata.getHttpStatusMessage());
                sb.append("\n");
                Log.e("HH", "onOpen - > " + sb.toString());
            }

            @Override
            public void onMessage(String message) {
                Message handlerMessage = Message.obtain();
                handlerMessage.obj = message;
                Log.e("HH", "onMessage - > " + message);
//                handler.sendMessage(handlerMessage);
            }

            @Override
            public void onClose(int code, String reason, boolean remote) {
                sb.append("onClose at time：");
                sb.append(new Date());
                sb.append("\n");
                sb.append("onClose info:");
                sb.append(code);
                sb.append(reason);
                sb.append(remote);
                sb.append("\n");
                Log.e("HH", "onClose - > " + sb.toString());
//                showMessage.setText(sb.toString());
            }

            @Override
            public void onError(Exception ex) {
                Log.e("HH", "onError - > " + ex.getMessage());
                sb.append("onError at time：");
                sb.append(new Date());
                sb.append("\n");
                sb.append(ex);
                sb.append("\n");
                Log.e("HH", "onError - > " + sb.toString());
//                showMessage.setText(sb.toString());
            }
        };
        webSocketClient.connect();

    }

    private void testWebSocket(String url) {
        client = new OkHttpClient.Builder()
                .readTimeout(3, TimeUnit.SECONDS)//设置读取超时时间
                .writeTimeout(3, TimeUnit.SECONDS)//设置写的超时时间
                .connectTimeout(3, TimeUnit.SECONDS)//设置连接超时时间
                .addInterceptor(new HttpHeaderInterceptor())
                .build();
        request = new Request.Builder().url(url).build();
        client.newWebSocket(request, createListener());
    }

    private WebSocketListener createListener() {
        return new WebSocketListener() {
            @Override
            public void onOpen(WebSocket webSocket, Response response) {
                super.onOpen(webSocket, response);
                Log.d(TAG, "open:" + response.toString());
                mWebSocket = webSocket;
//                webSocket.send("im ok");
            }

            @Override
            public void onMessage(WebSocket webSocket, String text) {
                super.onMessage(webSocket, text);
                Log.d(TAG, " 1111111 open:" + text);
            }

            @Override
            public void onMessage(WebSocket webSocket, ByteString bytes) {
                super.onMessage(webSocket, bytes);
                Log.d(TAG, " 22222222 open:" + bytes.toString());
            }

            @Override
            public void onClosing(WebSocket webSocket, int code, String reason) {
                super.onClosing(webSocket, code, reason);
                Log.d(TAG, " onClosing:" + reason);
            }

            @Override
            public void onClosed(WebSocket webSocket, int code, String reason) {
                super.onClosed(webSocket, code, reason);
                Log.d(TAG, " onClosed:" + reason);
            }

            @Override
            public void onFailure(WebSocket webSocket, Throwable t, Response response) {
                super.onFailure(webSocket, t, response);
                Log.d(TAG, " onFailure: ->" + t.getMessage());
            }
        };
    }

    /**
     * 读取数据
     *
     * @return 读取到的数据
     */
    private List<Map<String, String>> getDataList() {
        // 1.获得ContentResolver
        resolver = getContentResolver();
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_CALL_LOG) != PackageManager.PERMISSION_GRANTED) {
        }
        // 2.利用ContentResolver的query方法查询通话记录数据库
        /**
         * @param uri 需要查询的URI，（这个URI是ContentProvider提供的）
         * @param projection 需要查询的字段
         * @param selection sql语句where之后的语句
         * @param selectionArgs ?占位符代表的数据
         * @param sortOrder 排序方式
         */
        Cursor cursor = resolver.query(callUri, // 查询通话记录的URI
                columns
                , null, null, CallLog.Calls.DEFAULT_SORT_ORDER// 按照时间逆序排列，最近打的最先显示
        );
        // 3.通过Cursor获得数据
        List<Map<String, String>> list = new ArrayList<>();
        while (cursor.moveToNext()) {
            String name = cursor.getString(cursor.getColumnIndex(CallLog.Calls.CACHED_NAME));
            String number = cursor.getString(cursor.getColumnIndex(CallLog.Calls.NUMBER));
            long dateLong = cursor.getLong(cursor.getColumnIndex(CallLog.Calls.DATE));
            String date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date(dateLong));
            String time = new SimpleDateFormat("HH:mm").format(new Date(dateLong));
            int duration = cursor.getInt(cursor.getColumnIndex(CallLog.Calls.DURATION));
            int type = cursor.getInt(cursor.getColumnIndex(CallLog.Calls.TYPE));

            Log.e("HH", "NAME -> " + name
                    + ";number -> " + number + ";date -> " + date + ";" +
                    "time -> " + time + ";duration -> " + duration);
            String dayCurrent = new SimpleDateFormat("dd").format(new Date());
            String dayRecord = new SimpleDateFormat("dd").format(new Date(dateLong));
            String typeString = "";
            switch (type) {
                case CallLog.Calls.INCOMING_TYPE:
                    //"打入"
                    typeString = "打入";
                    break;
                case CallLog.Calls.OUTGOING_TYPE:
                    //"打出"
                    typeString = "打出";
                    break;
                case CallLog.Calls.MISSED_TYPE:
                    //"未接"
                    typeString = "未接";
                    break;
                default:
                    break;
            }
            Log.e("HH", "typeString -> " + typeString);
//            if (MobileUtil.isMobileNO(number1)) {
            String dayString = "";
            if ((Integer.parseInt(dayCurrent)) == (Integer.parseInt(dayRecord))) {
                //今天
                dayString = "今天";
            } else if ((Integer.parseInt(dayCurrent) - 1) == (Integer.parseInt(dayRecord))) {
                //昨天
                dayString = "昨天";
            } else {
                //前天
                dayString = "前天";
            }
            Log.e("HH", "dayString -> " + dayString);
//                long day_lead = TimeStampUtil.compareDayTime(date);
//                if (day_lead < 2) {//只显示48小时以内通话记录，防止通     //话记录数据过多影响加载速度
//                    Map<String, String> map = new HashMap<>();
//                    //"未备注联系人"
//                    map.put("name", (name == null) ? "未备注联系人" : name);//姓名
//                    map.put("number", number);//手机号
//                    map.put("date", date);//通话日期
//                    // "分钟"
//                    map.put("duration", (duration / 60) + "分钟");//时长
//                    map.put("type", typeString);//类型
//                    map.put("time", time);//通话时间
//                    map.put("day", dayString);//
//                    map.put("time_lead", TimeStampUtil.compareTime(date));//
//                    list.add(map);
//                } else {
//                    return list;
//                }
//            }
        }
        return list;
    }

    /**
     * 利用系统CallLog获取通话历史记录
     *
     * @param activity
     * @param num      要读取记录的数量
     * @return
     */
    public void getCallHistoryList(Activity activity, int num) {
        Cursor cs;
        if (ActivityCompat.checkSelfPermission(activity, Manifest.permission.READ_CALL_LOG)
                != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(activity,
                    new String[]{Manifest.permission.READ_CALL_LOG}, 1000);

        }
        if (ActivityCompat.checkSelfPermission(activity, Manifest.permission.READ_CONTACTS)
                != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(activity,
                    new String[]{Manifest.permission.READ_CONTACTS}, 1000);

        }
        cs = activity.getContentResolver().query(CallLog.Calls.CONTENT_URI, //系统方式获取通讯录存储地址
                new String[]{
                        CallLog.Calls.CACHED_NAME,  //姓名
                        CallLog.Calls.NUMBER,    //号码
                        CallLog.Calls.TYPE,  //呼入/呼出(2)/未接
                        CallLog.Calls.DATE,  //拨打时间
                        CallLog.Calls.DURATION,   //通话时长
                        CallLog.Calls.GEOCODED_LOCATION,
//                        getSimCarrierIdName
                        CallLog.Calls.CACHED_NUMBER_TYPE
                }, null, null, CallLog.Calls.DEFAULT_SORT_ORDER);
        int i = 0;

        if (cs != null && cs.getCount() > 0) {
            Log.e("HH", "callType = 11111111111111111");
            Date date = new Date(System.currentTimeMillis());
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
            String date_today = simpleDateFormat.format(date);
            for (cs.moveToFirst(); (!cs.isAfterLast()) && i < num; cs.moveToNext(), i++) {
                String callName = cs.getString(0);  //名称
                String callNumber = cs.getString(1);  //号码
                Log.e("HH", "callName = " + callName + ";callNumber = " + callNumber + ";json =>" + new Gson().toJson(cs));
                //如果名字为空，在通讯录查询一次有没有对应联系人
                if (callName == null || callName.equals("")) {
                    String[] cols = {ContactsContract.PhoneLookup.DISPLAY_NAME};
                    //设置查询条件
                    String selection = ContactsContract.CommonDataKinds.Phone.NUMBER + "='" + callNumber + "'";
                    Log.e("HH", "selection -》 " + selection);
                    Cursor cursor = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
                            cols, selection, null, null);
                    Log.e("HH", "selection -22》 " + selection);
                    if (cursor != null) {
                        int nameFieldColumnIndex = cursor.getColumnIndex(ContactsContract.PhoneLookup.DISPLAY_NAME);
                        Log.e("HH", "nameFieldColumnIndex = " + nameFieldColumnIndex);
                        if (cursor.getCount() > 0) {
                            cursor.moveToFirst();
                            callName = cursor.getString(nameFieldColumnIndex);
                            Log.e("HH", "callName = " + callName);
                        }
                        cursor.close();
                    }
                }
                //通话类型
                int callType = Integer.parseInt(cs.getString(2));
                Log.e("HH", "callType = " + callType);
                String callTypeStr = "";
                switch (callType) {
                    case CallLog.Calls.INCOMING_TYPE:
                        callTypeStr = "打入";
                        break;
                    case CallLog.Calls.OUTGOING_TYPE:
                        callTypeStr = "打出";
                        break;
                    case CallLog.Calls.MISSED_TYPE:
                        callTypeStr = "未接";
                        break;
                    default:
                        //其他类型的，例如新增号码等记录不算进通话记录里，直接跳过
                        Log.e("ssss", "" + callType);
                        i--;
                        continue;
                }
                //拨打时间
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                Date callDate = new Date(Long.parseLong(cs.getString(3)));
                String callDateStr = sdf.format(callDate);
                Log.e("HH", "callDateStr = " + callDateStr);
                if (callDateStr.equals(date_today)) { //判断是否为今天
                    sdf = new SimpleDateFormat("HH:mm");
                    callDateStr = sdf.format(callDate);
                } else if (date_today.contains(callDateStr.substring(0, 7))) { //判断是否为当月
                    sdf = new SimpleDateFormat("dd");
                    int callDay = Integer.valueOf(sdf.format(callDate));

                    int day = Integer.valueOf(sdf.format(date));
                    if (day - callDay == 1) {
                        callDateStr = "昨天";
                    } else {
                        sdf = new SimpleDateFormat("MM-dd");
                        callDateStr = sdf.format(callDate);
                    }
                } else if (date_today.contains(callDateStr.substring(0, 4))) { //判断是否为当年
                    sdf = new SimpleDateFormat("MM-dd");
                    callDateStr = sdf.format(callDate);
                }

                //通话时长
                int callDuration = Integer.parseInt(cs.getString(4));
                Log.e("HH", "callDuration = " + callDuration);
                int min = callDuration / 60;
                int sec = callDuration % 60;
                String callDurationStr = "";
                if (sec > 0) {
                    if (min > 0) {
                        callDurationStr = min + "分" + sec + "秒";
                    } else {
                        callDurationStr = sec + "秒";
                    }
                }
                String address = cs.getString(5);

                String address1 = cs.getString(6);
                /**
                 * callName 名字
                 * callNumber 号码
                 * callTypeStr 通话类型
                 * callDateStr 通话日期
                 * callDurationStr 通话时长
                 * 请在此处执行相关UI或存储操作，之后会查询下一条通话记录
                 */
                Log.e("Msg", "callName -> " + callName);
                Log.e("Msg", "callNumber -> " + callNumber);
                Log.e("Msg", "callTypeStr -> " + callTypeStr);
                Log.e("Msg", "callDateStr -> " + callDateStr);
                Log.e("Msg", "callDurationStr -> " + callDurationStr);
                Log.e("Msg", "address -> " + address);
                Log.e("Msg", "address1 -> " + address1);
                Log.e("Msg", "============================================== -> ");
                Log.e("Msg", "");
                Log.e("Msg", "\n");
            }
        }
    }

    /***
     * 给APP添加权限
     */
    private void initSDKPermission() {
        ApplicationManager.getInstance().setApplicationSettings(AppUtils.getPackageName(this),
//                ApplicationManager.FLAG_KEEP_ALIVE |
                        ApplicationManager.FLAG_GRANT_ALL_RUNTIME_PERMISSION |
                        ApplicationManager.FLAG_ALLOW_AUTOSTART
//                        |ApplicationManager.FLAG_PREVENT_UNINSTALLATION
                ,
                0);
    }


}